----------------------------
--LIB DOFILE
--Roland Yonaba (SeanPaul223)
--03/08/2010
----------------------------
 
-----------------------------------------------------------------------------
-- The main purpose of this library is helping Lua coders to 
-- debug their apps bypassing the in-built error screen,
-- which blocks the running process
 
-- Usage : call this file using require
-- Example: require 'libdofile'
-- When error screen is displayed, press Start to escape.
 
-- Seeks for Error type, Line, and desc in error string
function spliterr(str)
local g,e = string.find(str,':%d+')
local TYPE = string.sub(str,1,g-1)
local LINENUM = tonumber(string.sub(str,g+1,e))
local DESC = string.sub(str,e+2,str:len())
return TYPE,LINENUM,DESC
end
 
-- Custom Loop to display Error arguments.Escape this loop 
-- by pressing Start key
_USB = false
function showLoop(err,filename)
	while not Controls.read():start() do
	screen:clear()
	screen:print(10,10,"Byte - Compilation Error on file : "..filename,Color.new(255,255,255))
		if Controls.read():r() then 
			if _USB then 
			System.usbDiskModeDeactivate()
			_USB = false
			else System.usbDiskModeActivate()
			_USB = true
			end
		end
		if err then
		local TYPE,LINE,DESC = spliterr(err)
		screen:print(10, 20, 'ERROR TYPE: '..TYPE,Color.new(255,0,0))
		screen:print(10, 30, 'ERROR LINE: '..LINE,Color.new(255,255,0))
		screen:print(10, 40, 'DESCRIPTION: '..DESC,Color.new(255,255,255))
		screen:print(10, 50, 'R to activate/deactivate USB - Start to go back to the calling file',Color.new(255, 255, 255))
		screen:print(10, 50, 'Start to go back to the calling file', Color.new(255, 255, 255))
		screen.waitVblankStart()
		screen.flip()
		end
	end
end
 
 
--Main function
function dofile(filename)
    local file = assert(io.open(filename,"r"))
    if not file then
    showLoop(false,filename)
    return 
    end
    local f_size = file:seek("end")
    file:seek("set")
    local new_chunk = file:read(f_size)    
    local callresult,callerror = loadstring(new_chunk)
        if not callresult then 
        showLoop(callerror,filename)
        else
            local finalresult,err = pcall(callresult)
            if not result then 
            showLoop(err,filename)
            end
        end
end